from flask import jsonify, current_app
from werkzeug.utils import secure_filename
from config import Mail
import os
import re
from flask_mail import Message
import jwt
from threading import Thread
import datetime
from pprint import pprint


def allowed_file(filename):
    # :param filename: 文件名
    # :return: 布尔值，表示是否允许上传

    ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


def upload_image(upload_folder, file_storage):
    # 上传图片文件
    # :param self:
    # :param upload_folder: 上传文件夹路径
    # :param file_storage: 文件存储对象
    # :return: 上传后的文件名或错误信息

    if not os.path.exists(upload_folder):
        os.makedirs(upload_folder)

    if file_storage and allowed_file(file_storage.filename):
        filename = secure_filename(file_storage.filename)
        file_path = os.path.join(upload_folder, filename)
        file_storage.save(file_path)
        return {'filename': filename, 'file_path': file_path}
    else:
        return None


# 上传图片公共方法
def upload_img(files, upload_folder):
    if 'file' not in files:
        return jsonify({'code': '400', 'msg': '没有文件部分'})
    file_storage = files['file']
    if file_storage.filename == '':
        return jsonify({'code': '400', 'msg': '没有选择文件'})
    # pprint(file_storage)

    filename = upload_image(upload_folder, file_storage)
    # pprint(filename)
    if filename:
        return jsonify(
            {'code': '200', 'msg': '上传成功', 'filename': filename['filename'], 'file_path': filename['file_path']})
    else:
        return jsonify({'code': '400', 'msg': '上传失败，只支持png, jpg, jpeg, gif格式'})


# 删除文件的方法
def delete_file(path):
    # 判断路径是否存在
    if os.path.isfile(path):
        os.remove(path)
        return jsonify({'code': 200})
    else:
        return jsonify({'code: 400'})


# 返回富文本编辑器中的数据的图片路径@staticmethod
def Capture_image_path(body):
    pattern = r'<img[^>]+src="([^">]+)"'
    # 查找所有匹配项
    matches = re.findall(pattern, body)
    return matches


# 发送电子邮箱封装
def send_email(subject, email, html):
    # recipients是收件人的邮箱地址，subject是邮件的主题，html是邮件的HTML内容
    msg = Message(subject, sender=current_app.config['MAIL_USERNAME'], recipients=[email])
    # pprint(current_app.config['MAIL_USERNAME'])

    # 如果需要发送HTML格式的邮件，也可以设置
    msg.html = html

    # 异步
    try:
        with current_app.app_context():
            thread = Thread(target=Mail.send(msg))  # 异步发送
            thread.start()
            return {'code': 200, 'msg': "发送成功"}
    except Exception as e:
        return {'code': 400, 'msg': str(e)}


# jwt加密解密
def jwt_Encryption_decryption(status, datas):
    secret = current_app.config['SECRET_KEY']
    if status == 1:
        # 加密
        return {'code': 200, 'payload': jwt.encode(datas, secret, 'HS256'), 'msg': '生成成功'}
    else:
        # 解密
        # pprint(datas)
        try:
            payload = jwt.decode(datas, secret, 'HS256')
            return {'code': 200, 'payload': payload}
        except jwt.ExpiredSignatureError:  # JWT已过期
            return {'code': 400, 'payload': "", 'msg': '已过期'}
        except jwt.InvalidTokenError:  # JWT无效，例如，签名错误
            return {'code': 400, 'payload': "", 'msg': '验证错误'}
